﻿using CommonModel.ConsulModels;
using Consul;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ConsulAPI.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class ConsulHelperController : ControllerBase
    {
        private readonly ILogger<ConsulHelperController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ICapPublisher _capBus;

        public ConsulHelperController(ILogger<ConsulHelperController> logger, IConfiguration configuration, ICapPublisher capPublisher)
        {
            _logger = logger;
            _configuration = configuration;
            _capBus = capPublisher;
        }
        /// <summary>
        /// 服务注册
        /// </summary>
        /// <param name="consulRegister"></param>
        /// <returns></returns>
        [Route("ServiceRegister")]
        [HttpPost]
        public async Task<IActionResult> ServiceRegister(ConsulRegisterModel consulRegister)
        {
            try
            {
                //服务注册
                await AddServiceRegister(consulRegister);
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }

            return Ok();

        }

        /// <summary>
        /// 服务注册 订阅注册事件
        /// </summary>
        /// <param name="consulRegister"></param>
        /// <returns></returns>
        [NonAction]
        [CapSubscribe("ConsulAPI.ServiceRegister")]
        public async Task AddServiceRegister(ConsulRegisterModel consulRegister)
        {
            var consulClient = new ConsulClient(c =>
            {
                //consul地址
                c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]);
            });

            var registration = new AgentServiceRegistration()
            {
                ID = Guid.NewGuid().ToString(),//服务实例唯一标识
                Name = consulRegister.ServiceName,//服务名
                Address = consulRegister.ServiceIP, //服务IP
                Port = consulRegister.ServicePort,//服务端口 因为要运行多个实例，端口不能在appsettings.json里配置，在docker容器运行时传入
                Check = new AgentServiceCheck()
                {
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                    Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔
                    HTTP = $"http://{consulRegister.ServiceIP}:{consulRegister.ServicePort}{consulRegister.ServiceHealthCheck}",//健康检查地址
                    Timeout = TimeSpan.FromSeconds(5)//超时时间
                }
            };

            //服务注册
            await consulClient.Agent.ServiceRegister(registration);
        }
    }
}
